<?php

namespace app\api\controller\wechat;
use Think\Db;
use think\Controller;
class Apiwechat extends Controller
{
    private $config = [
        'appid'          => 'wx7c3d4b4c70cda90f',
        'appsecret'      => '8f12797c5b454ddc2c45b3413cf5687c'
    ];

    public function getOpenid(){
        if (request()->isPost()) {
            $post = input('post.');
            $code = isset($post['code']) && $post['code'] != '' ? $post['code'] : null;
            if(!$code){
                return json(array('code' => '0', 'msg' => 'code错误'));
            }
            $appid=$this->config['appid'];
            $appsecret= $this->config['appsecret'];
            $get_code_url = "https://api.weixin.qq.com/sns/jscode2session?appid=".$appid."&secret=".$appsecret."&js_code=".$code."&grant_type=authorization_code";
            $result = $this->httpGet($get_code_url);//请求拼接好的url
            $wxResult = json_decode($result, true);
            if($wxResult && $wxResult['openid']){
                return json(array('code' => '1', 'msg' => '请求成功','data'=>$wxResult));
            }
            return json(array('code' => '0', 'msg' => '请求失败'));
        } else {
            return json(array('code' => '0', 'msg' => '请求失败'));
        }
    }


    /**
     * 检验数据的真实性，并且获取解密后的明文.
     * @param $encryptedData string 加密的用户数据
     * @param $iv string 与用户数据一同返回的初始向量
     * @param $data string 解密后的原文
     *
     * @return int 成功0，失败返回对应的错误码
     */
    public function wxtel()
    {
        $post = input('post.');
        $sessionKey = isset($post['sessionKey']) && $post['sessionKey'] != '' ? $post['sessionKey'] : null;
        $encryptedData = isset($post['encryptedData']) && $post['encryptedData'] != '' ? $post['encryptedData'] : null;
        $iv = isset($post['iv']) && $post['iv'] != '' ? $post['iv'] : null;
        $appid=$this->config['appid'];
        if (strlen($sessionKey) != 24) {
            return json(array('code' => '0', 'msg' => '请求失败','data'=>$this->ErrorCode('IllegalAesKey')));
        }
        $aesKey = base64_decode($sessionKey);


        if (strlen($iv) != 24) {
            return json(array('code' => '0', 'msg' => '请求失败','data'=>$this->ErrorCode('IllegalIv')));
        }
        $aesIV = base64_decode($iv);

        $aesCipher = base64_decode($encryptedData);

        $result = openssl_decrypt($aesCipher, "AES-128-CBC", $aesKey, 1, $aesIV);

        $dataObj = json_decode($result);
        if ($dataObj == NULL) {
            return json(array('code' => '0', 'msg' => '请求失败','data'=>$this->ErrorCode('IllegalBuffer')));
        }
        if ($dataObj->watermark->appid != $appid) {
            return json(array('code' => '0', 'msg' => '请求失败','data'=>$this->ErrorCode('IllegalBuffer')));
        }
        return json(array('code' => '1', 'msg' => '请求成功','data'=>$result));
    }

    private function httpGet($url)
    {
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($curl, CURLOPT_TIMEOUT, 500);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($curl, CURLOPT_URL, $url);
        $res = curl_exec($curl);
        curl_close($curl);
        return $res;
    }



    /**
     * error code 说明.
     * <ul>
     *    <li>-41001: encodingAesKey 非法</li>
     *    <li>-41003: aes 解密失败</li>
     *    <li>-41004: 解密后得到的buffer非法</li>
     *    <li>-41005: base64加密失败</li>
     *    <li>-41016: base64解密失败</li>
     * </ul>
     */
    public function ErrorCode($code){
        $err=array(
            'OK'=>0,
            'IllegalAesKey'=>-41001,
            'IllegalIv'=>-41002,
            '$IllegalBuffer'=>-41003,
            'DecodeBase64Error'=>-41004
        );
    return $err[$code];
    }


    public function decryptData(){
        $post = input('post.');
        $sessionKey = isset($post['sessionKey']) && $post['sessionKey'] != '' ? $post['sessionKey'] : null;
        $encryptedData = isset($post['encryptedData']) && $post['encryptedData'] != '' ? $post['encryptedData'] : null;
        $iv = isset($post['iv']) && $post['iv'] != '' ? $post['iv'] : null;
        $appid=$this->config['appid'];
//        if (strlen($sessionKey) != 24) {
//            return json(array('msg'=>'sessionKey错误','code'=>0));
//        }
//        $aesKey=base64_decode($sessionKey);
//
//        if (strlen($iv) != 24) {
//            return json(array('msg'=>'iv错误','code'=>0));
//        }
//        $aesIV=base64_decode($iv);
//        $aesCipher=base64_decode($encryptedData);
//        $result=openssl_decrypt( $aesCipher, "AES-128-CBC", $aesKey, 1, $aesIV);
//        $dataObj=json_decode( $result );
//        if( $dataObj  == NULL )
//        {
//            return json(array('msg'=>'IllegalBuffer','code'=>0));
//        }
//        $appid=$this->config['appid'];
//        if ($dataObj->watermark->appid !=$appid) {
//            return json(array('msg'=>'IllegalBuffer错误','code'=>0));
//        }
//        return json(array('msg'=>'成功','code'=>1,'data'=>$dataObj));
//
//


        if (strlen($sessionKey) != 24) {
            return json(array('msg'=>'sessionKey错误','code'=>0));
        }
        $aesKey=base64_decode($sessionKey);

        if (strlen($iv) != 24) {
            return json(array('msg'=>'iv错误','code'=>0));
        }
        $aesIV=base64_decode($iv);

        $aesCipher=base64_decode($encryptedData);

        $result=openssl_decrypt( $aesCipher, "AES-128-CBC", $aesKey, 1, $aesIV);

        $dataObj=json_decode( $result );
        if( $dataObj  == NULL )
        {
            return json(array('msg'=>'IllegalBuffer','code'=>0));
        }
        if( $dataObj->watermark->appid != $appid )
        {
            return json(array('msg'=>'IllegalBuffer错误','code'=>0));
        }
        $data = $result;
        var_dump($data);
        return json(array('msg'=>'成功','code'=>1,'data'=>property_exists($data, 'unionid')?$data->unionid:null));
    }


}


